package com.yt.lxh.acl.service.impl;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.CircleCaptcha;
import com.yt.lxh.acl.service.ValidateCodeService;
import com.yt.lxh.constant.RedisEnum;
import com.yt.lxh.vo.system.ValidateCodeVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class ValidateCodeServiceImpl implements ValidateCodeService {
    @Autowired
    private RedisTemplate<String,String> redisTemplate;
    /**
     * 生成图片验证码
     * @return
     */
    @Override
    public ValidateCodeVo generateValidateCode() {
        //1 通过工具生成图片验证码
        //hutool
        //int width, int height, int codeCount, int circleCount
        //createCircleCaptcha：参数（宽，高，验证码位数，干扰线数量）
        CircleCaptcha circleCaptcha = CaptchaUtil.createCircleCaptcha(150, 48, 4, 10);
        //四位验证码的值
        String codeValue = circleCaptcha.getCode();
        //返回图片验证码，base64编码
        String imageBase64 = circleCaptcha.getImageBase64();
        //2 把验证码存储到redis里面，设置redis的key：UUID，redis的value：验证码值
        // 设置过期时间
        String key = UUID.randomUUID().toString().replaceAll("-","");
        redisTemplate.opsForValue().set(RedisEnum.ADMIN_VALIDATE.getMessage() +key,
                                        codeValue,
                                        5,
                                        TimeUnit.MINUTES);
        //3 返回ValidateCodeVo对象
        ValidateCodeVo validateCodeVo = new ValidateCodeVo();
        //redis存储数据key
        validateCodeVo.setCodeKey(key);
        validateCodeVo.setCodeValue("data:image/png;base64,"+imageBase64);
        return validateCodeVo;
    }
}
